package com.wct.permission.security;

import com.wct.permission.domain.SysPermission;
import com.wct.permission.domain.SysUser;
import com.wct.permission.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @author WEI (Email:changtan20000@163.com)
 * @description
 * @date 2020/2/10 16:56
 */
@Slf4j
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("username: {}", username);
        // 根据用户名从数据库中查询用户
        SysUser sysUser = sysUserMapper.selectByUsername(username);
        if (sysUser == null) {
            // 查询不到用户，抛出异常
            throw new UsernameException("用户名或密码错误");
        }

        MyUserDetails myUserDetails = new MyUserDetails();
        BeanUtils.copyProperties(sysUser, myUserDetails);

        log.info("myUserDetails1: {}", myUserDetails);

        // 方法1
/*        // 根据用户id查询角色id列表
        List<Integer> roleIdList = sysUserRoleMapper.selectByUserId(myUserDetails.getId());
        // 根据角色id查询权限id列表
        List<Integer> permissionIdList = sysRolePermissionMapper.selectPermissionIdByRoleIdLst(roleIdList);
        List<SysPermission> permissionList = sysPermissionMapper.selectByIdList(permissionIdList);
        StringBuffer stringBuffer = new StringBuffer();
        permissionList.forEach(permission -> {
            stringBuffer.append(permission.getTag());
            stringBuffer.append(",");

        });
        myUserDetails.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(stringBuffer.toString()));
        */

        // 方法2p
        // 根据用户名查询当前用户所有权限
        List<SysPermission> permissionList = sysUserMapper.findPermissionByUsername(username);
        List<GrantedAuthority> authorities = new ArrayList<>(permissionList.size());
        permissionList.forEach(permission -> authorities.add(new SimpleGrantedAuthority(permission.getTag())));
        myUserDetails.setAuthorities(authorities);

        log.info("myUserDetails2: {}", myUserDetails);

        return myUserDetails;
    }
}
